# 交易
import argparse
from strategy.strategy1 import Strategy1
from trading.trader import Trader
from risk.risk import RiskManager
from evaluation.evaluation import Evaluator
from chart.chart import Visualizer
from utils.data_loader import load_data
from utils.data_cleaner import clean_data
from config.config import *
from backtest.backteste import Backtester
from data.datahandle import dataHandle
from data.handle_pytdx import handlePytdx
import pandas as pd
from utils.logger import logger

# 定义事件类
class MarketDataEvent:
    def __init__(self, data):
        self.data = data
    
    def push_data(self, new_data):
        self.data = pd.concat([self.data, new_data])

def event_loop(strategy, data):
    event = MarketDataEvent(data[:1])
    for i in range(1, len(data)):
        event.push_data(data[i:i+1])
        strategy.on_bars(event)
        print(event[-1])
        if event[-1]['signal'] !=0:
            Trader(event[-1])
    return event

# 实时交易逻辑
def deal(args):
    # data = load_data(DATA_FILE_PATH)
    # data = clean_data(data)
    # strategy = Strategy1(data)
    # trader = Trader(strategy, data)
    # trader.execute_trades()
    pass

# 回测逻辑
def backtest(args):
    if(ONLINE_SOURCE_TYPE == 'pytdx'):
        handle = handlePytdx()
    data_handle = dataHandle(handle, args.stock_code)
    data = data_handle.get_data()

    strategy = Strategy1()
    event = event_loop(strategy, data)

    print(event.data)
    return data


# 实盘回测逻辑
def online_test(args):
    data = load_data(CONFIG_DATA_FILE_PATH)
    data = clean_data(data)
    data = data[data['stock_code'] == args.stock_code]  # 筛选指定股票代码的数据
    strategy = Strategy1(data)
    backtester = Backtester(strategy, data)
    cumulative_returns = backtester.run_backtest()
    risk_manager = RiskManager(cumulative_returns)
    max_drawdown, sharpe_ratio = risk_manager.calculate_risk_metrics()
    evaluator = Evaluator(cumulative_returns)
    total_return, annualized_return = evaluator.evaluate_performance()
    visualizer = Visualizer(cumulative_returns)
    visualizer.plot_cumulative_returns()
    print(f"Total Return: {total_return:.2%}")
    print(f"Annualized Return: {annualized_return:.2%}")
    print(f"Max Drawdown: {max_drawdown:.2%}")
    print(f"Sharpe Ratio: {sharpe_ratio:.2f}")


def main():
    parser = argparse.ArgumentParser(description='Stock Trading and Backtesting Framework')
    parser.add_argument('action', choices=['order', 'test', 'online'], help='Action to perform: order for live trading, test for backtesting')
    parser.add_argument('stock_code', nargs='?', default=None, help='Stock code for backtesting (required if action is test)')
    args = parser.parse_args()

    if args.action == 'order':
        deal(args)
    elif args.action == 'test':
        if args.stock_code is None:
            parser.error("The following arguments are required: stock_code")
        backtest(args)
    elif args.action == 'online':
        online_test(args)


if __name__ == "__main__":
    main()
